package com.pactera.demo.security.filter;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.pactera.demo.base.entity.Resource;
import com.pactera.demo.base.entity.Role;
import com.pactera.demo.base.service.IResourceService;
import com.pactera.demo.base.service.IRoleService;
import com.pactera.demo.common.exception.ResourceNotFoundException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.access.SecurityConfig;
import org.springframework.security.web.FilterInvocation;
import org.springframework.security.web.access.intercept.FilterInvocationSecurityMetadataSource;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
import org.springframework.security.web.util.matcher.RequestMatcher;
import org.springframework.util.AntPathMatcher;
import org.springframework.util.CollectionUtils;

import javax.servlet.http.HttpServletRequest;
import java.util.Collection;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * <p>
 *
 * </p>
 *
 * @author chang.zhou
 * @version version
 * @date Created in 2020/2/28 18:16
 */
public class DynamicFilterInvocationSecurityMetadataSource implements FilterInvocationSecurityMetadataSource {

    @Autowired
    private IResourceService resourceService;
    @Autowired
    private IRoleService roleService;

    @Override
    public Collection<ConfigAttribute> getAttributes(Object object) throws IllegalArgumentException {
        // 获取当前的请求
        final HttpServletRequest request = ((FilterInvocation) object).getRequest();
        //TODO 这里可以放到缓存中
        //获取系统中所有接口地址
        List<Resource> list = this.resourceService.list(new QueryWrapper<Resource>().lambda().eq(Resource::getResourceType, 1));
        //封装成Ant匹配器
        Set<AntPathRequestMatcher> requestMatchers = list.stream().map(x -> new AntPathRequestMatcher(x.getUri(), x.getMethodType())).collect(Collectors.toSet());
        //让数据库中所有的URI依次匹配当前的请求，如有匹配 拎出来
        AntPathRequestMatcher requestMatcher = requestMatchers.stream().filter(x -> x.matches(request)).findAny().orElseThrow(() -> new ResourceNotFoundException("404 资源未找到"));
        //用匹配到的 数据库中的uri去获取绑定了此URI的角色编码
        String pattern = requestMatcher.getPattern();
        Set<String> roleCodes = this.roleService.queryRolesByPattern(pattern,request.getMethod());
        //此编码即是SPRING控制该资源的关键
        return CollectionUtils.isEmpty(roleCodes) ? null : SecurityConfig.createList(roleCodes.toArray(new String[0]));
    }

    @Override
    public Collection<ConfigAttribute> getAllConfigAttributes() {
        List<Role> list = this.roleService.list();
        Set<String> roleCodes = list.stream().map(x -> x.getRoleCode()).collect(Collectors.toSet());
        return CollectionUtils.isEmpty(roleCodes) ? null : SecurityConfig.createList(roleCodes.toArray(new String[0]));
    }

    @Override
    public boolean supports(Class<?> aClass) {
        return FilterInvocation.class.isAssignableFrom(aClass);
    }
}
